package com.guigu.config;

import com.guigu.handler.MyAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;
    @Autowired
    private UserDetailsService userDetailsService;

    //用于自动登录，注入数据源
    @Autowired
    private DataSource dataSource;

    //用于记住我和自动登录
    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        //jdbcTokenRepository.setCreateTableOnStartup(true); //自动创表
        return jdbcTokenRepository;
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 自定义设置登录页面,不需要认证可以访问
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //设置403页面
//        http.exceptionHandling().accessDeniedPage("/unauth.html");
          http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);
        //设置退出
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/test/hello").permitAll();

        //表单认证
        http.formLogin()   //自定义自己编写的登录页面
            .loginPage("/login.html")     //登录页面设置
            .loginProcessingUrl("/user/login")    //登录访问路径
            .defaultSuccessUrl("/success.html").permitAll() //登录成功后，跳转路径

            .and().authorizeRequests()
            .antMatchers("/","/test/hello","/user/login").permitAll()//设置哪些路径可以直接访问，不需要认证
                //测试第一个方法hasAuthority()
                //(1)当前登录用户只有具有admins权限才可以访问这个路径
                // .antMatchers("/test/index").hasAuthority("admins")
                //(2)用户具有多个权限
                //.antMatchers("/test/index").hasAnyAuthority("admins,emp")
                //(3)ROLE_salary  源码会拼接ROLE_
                //.antMatchers("/test/index").hasRole("salary")
                //(4)hasAnyRole
                .antMatchers("/test/index").hasAnyRole("salary")
//                .anyRequest().authenticated()
                .anyRequest().access("@myServiceImpl.hasPerssion(request,authentication)")
                .and().rememberMe().tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(60)
                .userDetailsService(userDetailsService)
            .and().csrf().disable();  //关闭csrf防护


    }
}
